package com.example.demo.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.example.demo.config.AliyunConfig;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.bean.UploadResult;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class FileService {

    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private OSSClient ossClient;
    // 允许上传的格式
    private static final Set<String> IMAGE_TYPE = new HashSet<>(Arrays.asList(".jpg", ".jpeg", ".png"));

    /**
     * 文件上传
     * @param multipartFile
     * @return
     */
    public UploadResult upload(MultipartFile multipartFile) {

        UploadResult upLoadResult = new UploadResult();
        String fileName = multipartFile.getOriginalFilename();
        // 校验图片格式
        String fileType = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        if (!IMAGE_TYPE.contains(fileType)) {
            upLoadResult.setStatus("error");
            upLoadResult.setResponse("illegal media type");
            return upLoadResult;
        }
        // 校验文件大小, 超过 5M 为非法文件
        if (multipartFile.getSize()>  5 * 1024 * 1024) {
            upLoadResult.setStatus("error");
            upLoadResult.setResponse("file too large, file size must below 5M");
            return upLoadResult;
        }

        String filePath = getFilePath(fileName);
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.addUserMetadata("originName", fileName);
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(multipartFile.getBytes()), metadata);
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            upLoadResult.setStatus("error");
            upLoadResult.setResponse("file upload fail, some thing may be wrong");
            return upLoadResult;
        }
        upLoadResult.setStatus("done");
        upLoadResult.setName(aliyunConfig.getUrlPrefix() + filePath);
        upLoadResult.setUid(filePath);
        return upLoadResult;
    }

    /**
     * 文件下载
     * @param url
     * @param response
     */
    public boolean download(String url, HttpServletResponse response) {
        OSSObject object = ossClient.getObject(aliyunConfig.getBucketName(), url);
        if (object == null) return false;
        byte[] buf = new byte[1024];
        int len;
        try(InputStream in = object.getObjectContent(); ServletOutputStream out = response.getOutputStream()) {
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除文件
     * @param url
     * @return
     */
    public boolean delete(String url) {
        ossClient.deleteObject(aliyunConfig.getBucketName(), url);
        return true;
    }

    // 生成不重复的文件路径和文件名
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }


}
